<template>
  <a-modal title="新增用户" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="userAddVisiable">
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="法人行号" v-bind="formItemLayout">
            <a-input v-decorator="['instId']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='用户类型' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%"
              v-decorator="['userType', { rules: [{ required: true, message: '请选择用户类型' }] }]">
              <a-select-option key="00">统一支付平台内管</a-select-option>
              <a-select-option key="01">商户服务</a-select-option>
              <a-select-option key="02">第三方应用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='用户登录账号' v-bind="formItemLayout" :validateStatus="loginIdvalidateStatus"
            :help="loginIdhelp">
            <a-input @blur="handleloginIdBlur"
              v-decorator="['loginId', { rules: [{ required: true, message: '用户登录账号不能为空' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='用户名' v-bind="formItemLayout" :validateStatus="validateStatus" :help="help">
            <a-input @blur="handleUserNameBlur"
              v-decorator="['userName', { rules: [{ required: true, message: '用户名不能为空' }] }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='昵称' v-bind="formItemLayout">
            <a-input v-decorator="['nickName']" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='性别' v-bind="formItemLayout">
            <a-radio-group v-decorator="['userSex', { rules: [{ required: true, message: '请选择性别' }] }]">
              <a-radio value="0">男</a-radio>
              <a-radio value="1">女</a-radio>
              <a-radio value="2">保密</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='生日' v-bind="formItemLayout">
            <a-date-picker placeholder="请选择日期" name="reconFileDate"
              v-decorator="['birthday', { rules: [{ required: true, message: '请输入生日日期' }] }]" format="YYYYMMDD" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='密码' v-bind="formItemLayout">
            <a-tooltip title='新用户默认密码'>
              <a-input type='password' readOnly v-decorator="['loginPassword', { initialValue: defaultPassword }]" />
            </a-tooltip>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='邮箱' v-bind="formItemLayout">
            <a-input v-decorator="['email', {
              rules: [
                { type: 'email', message: '请输入正确的邮箱' },
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="手机" v-bind="formItemLayout">
            <a-input v-decorator="['mobileNo', {
              rules: [{ required: true, message: '请输入手机号' },
              { pattern: '^1[3-9]{1}[0-9]{9}$', message: '请输入正确的手机号' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='证件类型' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%"
              v-decorator="['certType', { rules: [{ required: true, message: '请选择证件类型' }] }]">
              <a-select-option key="01">身份证</a-select-option>
              <a-select-option key="02">军官证</a-select-option>
              <a-select-option key="03">护照</a-select-option>
              <a-select-option key="04">户口薄</a-select-option>
              <a-select-option key="05">士兵证</a-select-option>
              <a-select-option key="06">港澳来往内地通行证</a-select-option>
              <a-select-option key="07">台湾同胞来往内地通行证</a-select-option>
              <a-select-option key="08">临时身份证</a-select-option>
              <a-select-option key="09">外国人居留证</a-select-option>
              <a-select-option key="10">警官证</a-select-option>
              <a-select-option key="99">其它</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='证件号码' v-bind="formItemLayout">
            <a-input v-decorator="['certNo', {
              rules: [
                { pattern: '^[a-zA-Z1-9][a-zA-Z0-9]{0,30}$', message: '请输入正确的证件号码' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='角色' v-bind="formItemLayout">
            <a-select mode="multiple" :allowClear="true" style="width: 100%"
              v-decorator="['roleId', { rules: [{ required: true, message: '请选择角色' }] }]">
              <a-select-option v-for="r in roleData" :key="r.id">{{ r.roleName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属机构' v-bind="formItemLayout">
            <a-tree-select :allowClear="true" :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
              :treeData="orgTreeData" v-decorator="['orgId', { rules: [{ required: true, message: '请选择所属机构' }] }]">
            </a-tree-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 4rem!important;">
        <a-col :md="12" :sm="24">
          <a-form-item label='状态' v-bind="formItemLayout">
            <a-radio-group v-decorator="['userStatus', { rules: [{ required: true, message: '请选择状态' }] }]">
              <a-radio value="00">正常</a-radio>
              <a-radio value="01" checked>注销</a-radio>
              <a-radio value="02" checked>冻结</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
import { mapState } from 'vuex'
import moment from "moment";
moment.locale('zh-cn');

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'UserAdd',
  props: {
    userAddVisiable: {
      default: false
    },
    userInst: '',
    userOrgCode: '',
    currentUser: {
      isAdmin: false
    }
  },
  data() {
    return {
      user: {
        userName: ''
      },
      loading: false,
      roleData: [],
      orgTreeData: [],
      formItemLayout,
      defaultPassword: '',
      form: this.$form.createForm(this),
      validateStatus: '',
      help: '',
      loginIdvalidateStatus: '',
      loginIdhelp: '',
      idToOrgCodeData: []
    }
  },
  computed: {
    show: {
      get: function () {
        return this.userAddVisiable
      },
      set: function () {
      }
    }
  },
  mounted() {
    console.log(2);
  },
  methods: {
    reset() {
      this.validateStatus = ''
      this.help = ''
      this.user.userName = ''
      this.loading = false
      this.form.resetFields()
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },
    async handleSubmit() {
      await this.handleUserNameBlur();
      // this.handleloginIdBlur();
      if (this.validateStatus === 'success') {
        let loginId = this.form.getFieldValue('loginId');
        let instId = this.form.getFieldValue('instId');
        loginId = typeof loginId === 'undefined' ? '' : loginId.trim();
        if (loginId = '') {
          this.loginIdvalidateStatus = 'error'
          this.loginIdhelp = '用户登录账号不能为空！'
        } else {
          await this.$get(`admin/upmpuser/queryUserByLoginId`, {
            instId: instId,
            loginId: loginId
          }).then((r) => {
            if (r.data.length == 0) {
              this.loginIdvalidateStatus = 'success'
              this.loginIdhelp = ''
              this.submitForm();
            } else {
              this.loginIdvalidateStatus = 'error'
              this.loginIdhelp = '抱歉，用户登录账号已存在'
            }
          })
        }

      }
    },
    submitForm() {
      this.form.validateFields((err, values) => {
        if (!err && this.validateStatus === 'success') {
          this.setUserFields()
          this.loading = true
          this.user.roleId = this.user.roleId.join(',')
          this.user.orgCode = this.idToOrgCodeData[this.user.orgId];
          this.$post('admin/upmpuser', {
            ...this.user
          }).then((res) => {
            if (res.data.status) {
              this.reset()
              this.$emit('success')
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    async handleUserNameBlur() {
      let instId = this.form.getFieldValue('instId');
      let userName = this.form.getFieldValue('userName')
      userName = typeof userName === 'undefined' ? '' : userName.trim()
      if (userName.length) {
        if (userName.length > 10) {
          this.validateStatus = 'error'
          this.help = '用户名不能超过10个字符'
        } else if (userName.length < 4) {
          this.validateStatus = 'error'
          this.help = '用户名不能少于4个字符'
        } else {
          this.validateStatus = 'validating'
          await this.$get(`admin/upmpuser/check/`, {
            instId: instId,
            username: userName
          }).then((r) => {
            if (r.data) {
              this.validateStatus = 'success'
              this.help = ''
            } else {
              this.validateStatus = 'error'
              this.help = '抱歉，该用户名已存在'
            }
          })
        }
      } else {
        this.validateStatus = 'error'
        this.help = '用户名不能为空'
      }
    },
    async handleloginIdBlur() {
      let loginId = this.form.getFieldValue('loginId');
      let instId = this.form.getFieldValue('instId');
      loginId = typeof loginId === 'undefined' ? '' : loginId.trim()
      if (loginId.length) {
        this.loginIdvalidateStatus = 'validating'
        await this.$get(`admin/upmpuser/queryUserByLoginId`, {
          instId: instId,
          loginId: loginId
        }).then((r) => {
          if (r.data.length === 0) {
            this.loginIdvalidateStatus = 'success'
            this.loginIdhelp = ''
          } else {
            this.loginIdvalidateStatus = 'error'
            this.loginIdhelp = '抱歉，用户登录账号已存在'
          }
        })
      } else {
        this.loginIdvalidateStatus = 'error'
        this.loginIdhelp = '用户登录账号不能为空'
      }
    },
    setUserFields() {
      let values = this.form.getFieldsValue(['instId', 'userType', 'loginId', 'userName', 'nickName', 'userSex', 'loginPassword', 'birthday', 'email', 'mobileNo', 'certType', 'certNo', 'roleId', 'orgId', 'userStatus'])
   
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => {
          if ("birthday" == _key) {
            if (values[_key].constructor == String) {
              this.user.birthday = values.birthday;
            } else {
              this.user.birthday = values.birthday.format('YYYYMMDD');
            }
          } else {
            this.user[_key] = values[_key]
          }
        })
      }
      // this.user.userName = values.userName
      // this.user.password = values.password
      // this.user.email = values.email
      // this.user.mobile = values.mobile
      // this.user.roleId = values.roleId
      // this.user.deptId = values.deptId
      // this.user.userStatus = values.userStatus
      // this.user.ssex = values.ssex
    }
  },
  watch: {
    userAddVisiable() {
      if (this.userAddVisiable) {
        let role = {};
        role.instId = this.userInst;
        this.$get('admin/upmprole/getAll', { ...role }).then((r) => {
          this.roleData = r.data
        })
        let params = {}
        params.instId = this.userInst;
        if (this.currentUser.admin) {
          /*if(this.currentUser.instId == this.userInst){//默认法人行管理员选择默认法人行
              //不需要设置机构参数
          }else{
              //不需要设置机构参数
          }*/
        } else {
          params.orgCode = this.userOrgCode
        }
        this.$get('admin/upmporg', { ...params }
        ).then((r) => {
          this.orgTreeData = r.data.rows.children
          this.idToOrgCodeData = r.data.idToCode
        })
        this.form.getFieldDecorator('instId');
        this.form.setFieldsValue({
          "instId": this.userInst
        })
        this.form.getFieldDecorator('userType');
        this.form.setFieldsValue({
          // "instId":this.userInst,
          "userType": "00"
        })
      }
    }
  }
}
</script>
